package xyz.scootaloo.mono.security.web

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
import xyz.scootaloo.mono.base.lang.R
import xyz.scootaloo.mono.base.lang.SC
import xyz.scootaloo.mono.security.service.AccountService
import xyz.scootaloo.mono.security.web.dto.LoginFormVO
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 注册, 登陆, 登出
 *
 * @author flutterdash@qq.com
 * @since 2021/7/27 11:02
 */
@RestController
@RequestMapping("/account")
class AccountController {

    @Autowired lateinit var accountService: AccountService

    @PostMapping("/login")
    fun login(
        @RequestBody loginForm: LoginFormVO,
        request: HttpServletRequest,
        response: HttpServletResponse
    ): R<Void> {
        val loginResult = accountService.login(loginForm, request, response)
        return if (loginResult.success) {
            R.success(SC.LOGIN_SUCCESS)
        } else {
            if (loginResult.hasException())
                R.fail(SC.SERVER_INTERNAL_ERROR)
            else
                R.fail(SC.USERNAME_OR_PASSWORD_MISTAKE)
        }
    }

    @PostMapping("/register")
    fun register(@RequestBody loginForm: LoginFormVO, request: HttpServletRequest): R<Void> {
        val registerResult = accountService.register(request, loginForm)
        if (registerResult.success)
            return R.success(SC.REGISTER_SUCCESS)
        return R.fail(registerResult.get())
    }

    @GetMapping("/logout")
    fun logout(): R<Void> {
        accountService.logout()
        return R.success()
    }

}
